package net.kong.sns.rest.client.user;

import net.kong.sns.rest.client.method.JsonMethodInvokeBase;
import net.kong.sns.rest.client.model.UserAuth;
import net.kong.sns.rest.client.model.UserAuthImpl;
import net.kong.sns.rest.client.KongApiMethod;
import net.kong.sns.rest.client.InvalidResponseException;
import net.kong.sns.rest.client.rest.HttpResponseContent;
import net.kong.org.springframework.util.StringUtils;

import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.List;
import java.util.Arrays;

/**
 * @author <a href="mailto:lanhuai@gmail.com">Ning Yubin</a>
 * @version $Id: UserAuthMethodInvoke.java,v 1.3 2009/11/04 17:17:38 ningyubin Exp $
 */
public class UserAuthMethodInvoke extends JsonMethodInvokeBase<Set<UserAuth>> {
    public UserAuthMethodInvoke(Long[] userIds, String sessionKey) {
        super(KongApiMethod.USERS_IS_APP_USER, sessionKey);
        setParameter("user_id", StringUtils.arrayToCommaDelimitedString(userIds));
    }

    public UserAuthMethodInvoke(Long[] userIds) {
        this(userIds, "");
    }

    public UserAuthMethodInvoke(String sessionKey) {
        super(KongApiMethod.USERS_IS_APP_USER, sessionKey);
    }

    @Override
    protected Set<UserAuth> processJsonResponse(HttpResponseContent responseData) throws InvalidResponseException {
        String response = responseData.getBody();
        Object o = reader.read(response);
        Set<String> initializedFields = new HashSet<String>();
        initializedFields.addAll(StringUtils.commaDelimitedListToSet((StringUtils.arrayToCommaDelimitedString(UserAuth.Field.values()))));

        Set<UserAuth> userAuths = new HashSet<UserAuth>();

        List<Map<String, Object>> userList = (List<Map<String, Object>>) o;
        for (Map<String, Object> map : userList) {
            UserAuthImpl userAuth = new UserAuthImpl();
            userAuth.initialize(map, initializedFields);
            userAuths.add(userAuth);
        }

        return userAuths;
    }
}
